package com.idbk.chargestation.activity.assist;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AlertDialog.Builder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.BuildConfig;
import com.idbk.chargestation.R;
import com.idbk.chargestation.app.ManagerCache;
import com.idbk.chargestation.app.ManagerUpdate;
import com.idbk.chargestation.app.MyVersion;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.util.CheckUtil;

/**
 * 设置
 *
 * @author zhx
 */
public class ActivitySetting extends BaseActivity implements OnClickListener {

    private Context mContext;
    private TextView mTextVersion, mTextCacheSize;
    private String version;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_setting);

        mContext = ActivitySetting.this;

        setupView();

        setupData();
    }

    @SuppressWarnings("ConstantConditions")
    private void setupView() {
        RelativeLayout mServer = (RelativeLayout) findViewById(R.id.layout_server);

        findViewById(R.id.toolbar_back).setOnClickListener(this);
        findViewById(R.id.layout_operation).setOnClickListener(this);
        findViewById(R.id.layout_license).setOnClickListener(this);
        findViewById(R.id.layout_cache).setOnClickListener(this);
        findViewById(R.id.layout_version).setOnClickListener(this);
        findViewById(R.id.layout_about).setOnClickListener(this);
        mServer.setOnClickListener(this);
        version = MyVersion.getVersion(mContext);
        if (BuildConfig.SERVER_DEBUG) {
            mServer.setVisibility(View.VISIBLE);
        } else {
            mServer.setVisibility(View.GONE);
        }

        mTextVersion = (TextView) findViewById(R.id.activity_setting_textview_version);
        findViewById(R.id.activity_setting_textview_exit).setOnClickListener(this);

        mTextCacheSize = (TextView) findViewById(R.id.activity_setting_textview_cache_size);
        RelativeLayout mShare = (RelativeLayout) findViewById(R.id.layout_share);
        if (MyVersion.VERSION_NJYX.equals(version)) {
            mShare.setVisibility(View.VISIBLE);
            mShare.setOnClickListener(this);
        } else {
            mShare.setVisibility(View.GONE);
        }
    }

    private void setupData() {
        mTextVersion.setText(getVersion());
        String cacheSize = ManagerCache.getCacheSize(this) + "MB";
        mTextCacheSize.setText(cacheSize);
    }

    private String getVersion() {
        String version = "当前版本：V1.0.0";
        try {
            PackageManager manager = mContext.getPackageManager();
            PackageInfo info = manager.getPackageInfo(
                    mContext.getPackageName(), 0);
            if (BuildConfig.SERVER_DEBUG) {
                // 测试版本添加版本码以做识别;
                version = "当前版本：V" + info.versionName + "." + info.versionCode;
            } else {
                version = "当前版本：V" + info.versionName;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    //监听事件
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_back:
                finish();
                break;
            case R.id.activity_setting_textview_exit:
                exitApplication();//退出
                break;
            case R.id.layout_server:
                serverChooseDialog();
                break;
            case R.id.layout_about:
                if (version.equals(MyVersion.VERSION_NJYX)) {
                    Intent intentInt = new Intent(ActivitySetting.this, ActivityIntroduction.class);
                    startActivity(intentInt);
                } else {
                    Intent intent = new Intent(ActivitySetting.this, ActivityAbout.class);
                    startActivity(intent);
                }
                break;
            case R.id.layout_cache:
                cleanCache();
                break;
            case R.id.layout_version:
                checkVersion();
                break;
            case R.id.layout_license:
                showLicense();
                break;
            case R.id.layout_operation:
                help();
                break;
            case R.id.layout_share:
                Intent intentShare = new Intent(ActivitySetting.this, ActivityQrCode.class);
                startActivity(intentShare);
                break;
            default:
                break;
        }
    }

    //清理缓存
    private void cleanCache() {
        new Builder(mContext)
                .setMessage("你确定要删除缓存吗？")
                .setNegativeButton(android.R.string.cancel, null)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ManagerCache.cleanCache(mContext);
                        final AlertDialog tip = new Builder(mContext)
                                .setMessage("操作完成！")
                                .create();
                        tip.show();
                        mTextCacheSize.postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                tip.dismiss();
                                setupData();
                            }
                        }, 1000);
                    }
                })
                .create()
                .show();
    }

    //操作指引
    private void help() {
        Intent intent = new Intent(this, ActivityHelp.class);
        startActivity(intent);
    }

    private void showLicense() {
        Intent intent = new Intent(this, ActivityLicense.class);
        startActivity(intent);
    }

    //检查更新
    private void checkVersion() {
        new ManagerUpdate(mContext, true).checkUpdate();
    }

    //退出系统
    private void exitApplication() {
        //确认操作对话局框
        new Builder(mContext)
                .setTitle(R.string.common_dialog_tip)
                .setMessage("你确定要退出应用？")
                .setCancelable(true)
                .setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // CATEGORY_HOME以上的活动全部清除；
                        startActivity(intent);
                        android.os.Process.killProcess(android.os.Process.myPid()); //中断当当前线程；
                        System.exit(0);   //退出应用，返回值为0代表正常退出
                    }
                })
                .setNegativeButton(R.string.common_cancel, null)
                .create()
                .show();
    }

    private void serverChooseDialog() {
        String[] aUrls = new String[]{
                "阿里云服务器(中能易电) api.eastevs.com",//阿里云服务器(中能易电)，120.24.6.21
                "内网服务器(马平东) 192.168.162.105", //内网服务器(马平东)
                "公网服务器(马平东) 218.16.97.171",  //公网服务器(马平东)
                "内网服务器(测试) 192.168.1.21",    //内网服务器(测试)
                "公网服务器(测试) 218.16.97.168",//公网服务器(测试)
                "阿里云服务器(南京业祥) 120.55.166.130",//阿里云服务器(南京业祥)
                "120.76.137.229",                 //陕西速能易电
                "阿里云服务器(中山粤盛) gdysyfb.com",				//阿里云服务器(中山粤盛)
        };
        final AppContext ac = AppContext.getInstance();
        final int index = ac.getWorkNetMode();
        new AlertDialog.Builder(this)
                .setTitle("请选择所选服务器")
                .setSingleChoiceItems(aUrls, index, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (index == which) {
                            return;
                        }
                        ac.setWorkNetMode(which);

                        String str = "服务器已更改，请<font color='red'>退出APP</font>重新进入刷新数据";
                        new Builder(mContext)
                                .setMessage(CheckUtil.textFromHtml(str))
                                .setPositiveButton(R.string.common_ok, null)
                                .create()
                                .show();
                    }
                })
                .create()
                .show();
    }


}
